export default {
	namespaced: true,
	state: () => ({
		cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
	}),
	mutations: {
		addToCart(state, goods) {
			// 添加的商品在购物车内有可能存在、有可能不存在
			const findGoods = state.cart.find(cartGoodsItem => cartGoodsItem.goods_id === goods.goods_id)
			if (!findGoods) {
				state.cart.push(goods)
				state.total += 1
			} else {
				findGoods.goods_count += 1
			}
			this.commit('cart/saveToStorage')
		},
		updateGoodsState(state, goods) {
			let findGoods = state.cart.find(v => v.goods_id === goods.goods_id)
			findGoods.goods_state = goods.goods_state
			this.commit('cart/saveToStorage')
		},
		updateGoodsCount(state, goods) {
			let findGoods = state.cart.find(v => v.goods_id === goods.goods_id)
			findGoods.goods_count = goods.goods_count
			this.commit('cart/saveToStorage')
		},
		updateAllGoodsState(state, newCheckState) {
			state.cart.forEach(goodsItem => goodsItem.goods_state = newCheckState)
			this.commit('cart/saveToStorage')
		},
		removeGoodsItem(state,goodsId) {
			state.cart = state.cart.filter(item => item.goods_id !== goodsId)
			this.commit('cart/saveToStorage')
		},
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		}
	},
	actions: {

	},
	getters: {
		species: state => state.cart.length,
		totalPrice: state => {
			return state.cart.filter(item => item.goods_state).reduce((prev,next) => {
				return prev += next.goods_count * next.goods_price
			},0)
		},
		isCheckedAll: state => state.cart.every(item => item.goods_state),
		hasBeenChecked: state => state.cart.some(item => item.goods_state)
	}
}
